package com.dfbz.controller.login;

import com.dfbz.constant.Const;
import com.dfbz.controller.BaseServlet;
import com.dfbz.model.User;
import com.dfbz.service.UserService;
import com.dfbz.service.impl.UserServiceImpl;
import com.dfbz.utils.MailUtil;
import com.dfbz.utils.StrUtil;

import javax.mail.MessagingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@WebServlet("/login/*")
public class LoginServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();


    public void toLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String remember = req.getParameter("remember");

        if (null != username && null != password) {
            User user = userService.findUserByName(username);
            if (null != user) {
                if (password.equals(user.getPassword())) {
                    if (null != remember) {
                        Cookie cookie = new Cookie("userInfo", username);
                        cookie.setMaxAge(Const.MAX_COOKIE_TIME);
                        cookie.setPath("/");
                        resp.addCookie(cookie);
                    }
                    userService.updateLoginTime(user.getId());
                    HttpSession session = req.getSession();
                    session.setAttribute("userId", user.getId());
                    session.setMaxInactiveInterval(Const.MAX_SESSION_TIME);
                    Map<String, Object> map = userService.findUserBaseById(user.getId());
                    req.getSession().setAttribute("userBaseInfo", map);
                    resp.sendRedirect(req.getContextPath() + "/view/home");
                    return;
                }
            }
        }
        resp.sendRedirect(req.getContextPath() + "/");
    }


    public void toLogout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Cookie[] cookies = req.getCookies();
        if (null != cookies && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if ("userInfo".equals(cookie.getName())) {
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    resp.addCookie(cookie);
                    break;
                }
            }
        }
        resp.sendRedirect(req.getContextPath() + "/");
    }


    public void toRegister(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String email = req.getParameter("email");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String password2 = req.getParameter("password2");

        if (StrUtil.checkEmail(email)) {
            if (null != username && null != password) {
                if (password.equals(password2)) {

                    User userByName = userService.findUserByName(username);
                    if (null != userByName) {
                        req.getSession().setAttribute("regErrorMsg", "该用户已存在");
                        resp.sendRedirect(req.getContextPath() + "/view/showRegister");
                    } else {
                        userService.addUser(email, username, password);
                        resp.sendRedirect(req.getContextPath() + "/view/index");
                    }

                    User userByEmail = userService.findUserByEmail(email);
                    if (null != userByEmail) {
                        req.getSession().setAttribute("regErrorMsg", "邮箱已存在");
                        resp.sendRedirect(req.getContextPath() + "/view/showRegister");
                    } else {
                        userService.addUser(email, username, password);
                        resp.sendRedirect(req.getContextPath() + "/view/index");
                    }

                } else {
                    req.getSession().setAttribute("regErrorMsg", "密码不一致");
                    resp.sendRedirect(req.getContextPath() + "/view/showRegister");
                }

            } else {
                req.getSession().setAttribute("regErrorMsg", "用户名和密码不能为空");
                resp.sendRedirect(req.getContextPath() + "/view/showRegister");
            }

        } else {
            req.getSession().setAttribute("regErrorMsg", "请输入正确的邮箱");
            resp.sendRedirect(req.getContextPath() + "/view/showRegister");
        }
    }

    public void sendEmailCode(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setHeader("content-Type", "text/html");
        String email = req.getParameter("email");
        HttpSession session = req.getSession();
        if (StrUtil.checkEmail(email)) {
            Object obj = session.getAttribute(email);
            if (null == obj) {
                try {
                    String title = "《小标交友》重置密码";
                    String code = StrUtil.createRandomNum();
                    String content = "您的验证码是：" + code;
                    session.setAttribute(email, code);
                    session.setMaxInactiveInterval(Const.MAX_CODE_TIME);
                    MailUtil.send(email, title, content, MailUtil.UNICODE);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                resp.getWriter().write("验证码发送成功，请查收");
            } else {
                resp.getWriter().write("验证码已发送到您的邮箱，请查收");
            }
        } else {
            resp.getWriter().write("邮箱格式不正确，请重新输入");
        }
    }


    public void resetNewPassword(HttpServletRequest req, HttpServletResponse resp) {
        try {
            String email = req.getParameter("email");
            String code = req.getParameter("emailCode");
            String password = req.getParameter("password");
            HttpSession session = req.getSession();
            if (StrUtil.checkEmail(email)) {
                Object obj = session.getAttribute(email);
                if (null != obj) {
                    String emailCode = obj.toString();
                    if (emailCode.equals(code)) {
                        User user = userService.findUserByEmail(email);
                        if (null != user) {
                            userService.resetNewPwd(user.getId(), password);
                            resp.sendRedirect(req.getContextPath() + "/view/index");
                            return;
                        }

                    }
                }
            }
            req.getSession().setAttribute("forgetErrorMsg", "重置失败");
            resp.sendRedirect(req.getContextPath() + "/view/forget");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
